import { ConfigEnv, loadEnv, UserConfig } from 'vite';
import process from 'node:process';
import { createVitePlugins } from './build/plugin';
import { resolve } from 'path';

const root = process.cwd();

function pathResolve(dir: string) {
  return resolve(root, '.', dir)
}

export default ({command, mode}: ConfigEnv): UserConfig => {
  const isBuild = command === 'build';
  const {VITE_TITLE, VITE_BASE_PATH, VITE_BUILD_COMPRESS, VITE_ENABLE_ANALYZE} = loadEnv(mode, root);
  return {
    base: VITE_BASE_PATH,
    plugins: createVitePlugins({
        isBuild,
        root,
        title: VITE_TITLE,
        enableAnalyze: VITE_ENABLE_ANALYZE === 'true',
        compress: VITE_BUILD_COMPRESS || ''
      }
    ),
    css: {
      preprocessorOptions: {
        scss: {api: 'modern-compiler'},
      }
    },
    resolve: {
      alias: [
        {
          find: /\/#\//,
          replacement: pathResolve('types') + '/',
        },
        {
          find: '@',
          replacement: pathResolve('src') + '/',
        },
      ],
      dedupe: ['vue'],
      extensions: ['.ts', '.js'],
    },
    // 编译打包配置
    build: {
      assetsDir: 'static',
      sourcemap: false, // 构建后是否生成 source map 文件
      chunkSizeWarningLimit: 2000,
      rollupOptions: {
        // 配置rollup输出选项
        output: {
          // 静态资源分拆打包
          manualChunks(id) {
            if (id.includes('node_modules')) {
              return id
                .toString()
                .split('node_modules/')[1]
                .split('/')[0]
                .toString();
            }
          },
          // 静态资源打包
          chunkFileNames: 'static/js/chunk-[hash:10].js', // 引入文件名的名称
          entryFileNames: 'static/js/chunk-[hash:10].js', // 包的入口文件名称
          // assetFileNames: 'static/[ext]/chunk-[hash:10].[ext]', // 资源文件像 字体，图片等
          assetFileNames: (chunkInfo: any) => {
            const info = chunkInfo.name.split('.');
            let extType = info[info.length - 1];
            // console.log('文件信息', chunkInfo.name)
            if (/\.(mp4|webm|ogg|mp3|wav|flac|aac)(\?.*)?$/i.test(chunkInfo.name)) {
              extType = 'media';
            } else if (/\.(png|jpe?g|gif|svg|webp)(\?.*)?$/.test(chunkInfo.name)) {
              extType = 'img';
            } else if (/\.(woff2?|eot|ttf|otf)(\?.*)?$/i.test(chunkInfo.name)) {
              extType = 'fonts';
            }
            return `static/${extType}/chunk-[hash:10].[ext]`;
          }
        },
      },

      minify: 'terser',
      terserOptions: {
        compress: {
          drop_console: true,   // 打包时删除 console
          drop_debugger: true,  // 打包时删除 debugger
        },
      }
    },
    server: {
      open: false,
      host: '0.0.0.0',
      port: 5174,
      // 跨域代理
      proxy: {
        '/admin': {
          target: 'http://pay.netwelive.com/sang',
          // target: 'https://dev.yujianhuawuyou.com/admin/admin',
          changeOrigin: true,
          rewrite: (path) => path.replace(new RegExp(`^/admin`), ''),
        },
      }
    },
  };
};
